package dao.impl;

import com.mysql.cj.jdbc.MysqlDataSource;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * The type Base dao.
 *
 * @author gzp
 * @create 2022 -12-12 10:04
 */
public class BaseDao {

    private static final String URL = "jdbc:mysql://127.0.0.1:3306/project?characterEncoding=utf8&useSSL=false";
    private static final String USER_NAME = "root";
    private static final String PASSWORD = "17208288992";
    private static final DataSource dataSource = null;
    /**
     * The Conn.
     */
    Connection conn = null;
    /**
     * The Pstmt.
     */
    PreparedStatement pstmt = null;
    /**
     * The Rs.
     */
    ResultSet rs = null;

    private BaseDao() {

    }

    private static DataSource getDataSource() {
        if (dataSource == null) {
            synchronized (BaseDao.class) {
                if (dataSource == null) {
                    final DataSource dataSource = new MysqlDataSource();
                    ((MysqlDataSource) dataSource).setUrl(URL);
                    ((MysqlDataSource) dataSource).setUser(USER_NAME);
                    ((MysqlDataSource) dataSource).setPassword(PASSWORD);
                    return dataSource;
                }
            }
        }
        return null;
    }

    /**
     * Gets connection.
     *
     * @return the connection
     */
    public static Connection getConnection() {
        try {
            return getDataSource().getConnection();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * Close.
     *
     * @param resultSet         the result set
     * @param preparedStatement the prepared statement
     * @param connection        the connection
     */
    public static void close(ResultSet resultSet, PreparedStatement preparedStatement, Connection connection) {
        if (resultSet != null) {
            try {
                resultSet.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (preparedStatement != null) {
            try {
                preparedStatement.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (connection != null) {
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}
